<template>
  <div class="system-info">
    <!-- 面包屑 -->
    <div class="bread-crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/home/processModel' }">流程模型</el-breadcrumb-item>
        <el-breadcrumb-item>模型设计</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="main-middle">
      <el-card class="box-card">
        <!-- 表单信息 -->
        <div class="card-title">流程模型信息</div>
        <el-form label-width="100px" :model="editForm" :rules="editFormRules" ref="editForm">
          <el-row :gutter="24">
             <el-col :span="8">
              <!-- 公司名称 -->
              <el-form-item label="公司名称" prop="compId">
                <el-select
                v-model="editForm.compId"
                filterable
                auto-complete="off"
                placeholder="请选择"
                style="width:100%;"
              >
                <el-option label="无" value></el-option>
                <!-- 循环所有角色 角色名称 角色ID -->
                <el-option
                  v-for="(item,index) in compList"
                  :key="index"
                  :label="item.compName"
                  :value="item.compId"
                ></el-option>
              </el-select>
              </el-form-item>
            </el-col>
             <el-col :span="8">
              <!-- 流程名称 -->
              <el-form-item label="流程编号" prop="flowId">
                <el-input v-model="editForm.flowId" auto-complete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <!-- 流程名称 -->
              <el-form-item label="流程名称" prop="flowName">
                <el-input v-model="editForm.flowName" auto-complete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <!-- 所属分类 -->
              <el-form-item label="所属分类" prop="flowType">
                <el-select v-model="editForm.flowType" style="width:100%;">
                  <el-option label="无" value=""></el-option>
                  <el-option label="工作审核" value="工作审核"></el-option>
                  <el-option label="项目审核" value="项目审核"></el-option>
                  <el-option label="人事审核" value="人事审核"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <!-- 关联表单 -->
              <el-form-item label="关联表单" prop="formId">
                <el-select
                v-model="editForm.formId"
                filterable
                auto-complete="off"
                placeholder="请选择"
                style="width:100%;"
              >
                <el-option label="无" value></el-option>
                <!-- 循环所有角色 角色名称 角色ID -->
                <el-option
                  v-for="(item,index) in formList"
                  :key="index"
                  :label="item.formName"
                  :value="item.formId"
                ></el-option>
              </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 备注说明 输入长度限制20-->
          <el-form-item label="备注说明">
            <el-input
              type="textarea"
              v-model="editForm.note"
              placeholder="备注说明（20字以内）"
              :rows="3"
              maxlength="20"
            ></el-input>
          </el-form-item>
          <el-form-item label="流程设计">
            <v-g-editor class="demo" ref="flowChart">
              <div class="demo-chart">
                <div class="demo-chart-header">
                  <flow-toolbar />
                </div>
                <div class="demo-chart-container">
                  <div class="demo-chart-sidebar">
                    <flow-item-panel />
                  </div>
                  <div class="demo-chart-main">
                    <flow
                      :data="flowChartData"
                      :graph="{ mode: 'readOnly' }"
                    />
                  </div>
                  <div class="demo-chart-panel">
                    <flow-detail-panel />
                    <editor-minimap />
                  </div>
                </div>
              </div>
              <flow-context-menu />
              <register-edge
                name="custom-polyline"
                extend="flow-polyline"
                :config="customEdgeConfig"
              />
            </v-g-editor>
          </el-form-item>
        </el-form>
        <div class="card-line">
          <!-- 返回 -->
          <el-button size="small" @click="goBack">返回</el-button>
           <!-- 确认修改 -->
          <el-button
            v-if="isEdit"
            type="primary"
            style="float:right"
            size="small"
            @click="onEdit"
            :disabled="isSubmit"
          >确认修改</el-button>
          <!-- 确认提交 -->
          <el-button
            v-if="!isEdit"
            type="primary"
            style="float:right"
            size="small"
            @click="onSubmit"
            :disabled="isSubmit"
          >确认提交</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
// 引入G6图可视化引擎
import VGEditor, { Flow, RegisterEdge } from 'vg-editor';
import { FlowToolbar } from '@/components/EditorToolbar';
import { FlowItemPanel } from '@/components/EditorItemPanel';
import { FlowDetailPanel } from '@/components/EditorDetailPanel';
import EditorMinimap from '@/components/EditorMinimap';
import { FlowContextMenu } from '@/components/EditorContextMenu';

import NodeData from '@/components/NodeData';

const data = {
  nodes: [],
  edges: []
};
export default {
  methods: {

    onFlow () {
      this.modalVisible = true;
      this.nodeData = this.flowChartData;
    },

    // 获取所有公司数据
    getCompList: function () {
      this.$http.post('api/findAllCompNoPage').then(res => {
        let { code, datas } = res;
        if (code === 0) {
          this.compList = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 获取所有表单数据
    getFormList: function () {
      this.$http
        .post('api/findAllForm')
        .then(res => {
          let { code, datas } = res;
          if (code === 0) {
            this.formList = datas;
          }
        })
        .catch(err => {
          if (err === undefined) {
            this.$message({
              message: '服务器响应异常！',
              type: 'error'
            });
            return false;
          }
        });
    },

    getDatas () {
      let nodeDB = this.$route.query.datas;
      if (nodeDB !== undefined) {
        this.isEdit = true;
        // 弹出窗表单初始数据
        this.editForm = {
          id: nodeDB.id,
          compId: nodeDB.compId,
          // 流程表
          flowId: nodeDB.flowId,
          flowName: nodeDB.flowName,
          flowType: nodeDB.flowType,
          formId: nodeDB.formId,
          note: nodeDB.note,
          flowJson: nodeDB.flowJson,
          // 流程节点表
          flowNode: [],
          // 流程线条表
          flowLine: []
        };
        let nodes = JSON.parse(nodeDB.flowJson);
        this.flowChartData = nodes;
      }
    },

    // 提交流程
    onSubmit () {
      // 防止重复提交
      this.isSubmit = true;
      setTimeout(() => {
        this.isSubmit = false;
      }, 1000);
      this.$nextTick(() => {
        let params = {
          formId: this.editForm.formId
        };

        this.$http.post('api/getFlowFormCount', params).then(res => {
          let { code, datas } = res;
          // 判断Code状态
          if (code === 0) {
            if (datas) {
              this.$message({
                message: '表单被占用！',
                type: 'error'
              });
            } else {
              // 收集请求数据
              let params = {
                compId: this.editForm.compId,
                // 流程表
                flowId: this.editForm.flowId,
                flowName: this.editForm.flowName,
                flowType: this.editForm.flowType,
                formId: this.editForm.formId,
                note: this.editForm.note,
                flowJson: '',
                // 流程节点表
                flowNode: [],
                // 流程线条表
                flowLine: []
              };

              let flows = this.$refs.flowChart.propsAPI.save();

              params.flowJson = JSON.stringify(flows);

              if (flows.nodes !== undefined) {
                flows.nodes.map(item => {
                  params.flowNode.push({
                    // 节点ID
                    id: item.id,
                    // 节点名称
                    name: item.label,
                    // 节点类型
                    type: item.type,
                    // 节点处理人
                    users: item.users
                  });
                });
              }
              if (flows.edges !== undefined) {
                flows.edges.map(ind => {
                  params.flowLine.push({
                    // 线条ID
                    id: ind.id,
                    // 线条名称
                    name: ind.label,
                    // 上一步节点
                    source: ind.source,
                    // 下一步节点
                    target: ind.target
                  });
                });
              }
              // 判断是否通过验证规则验证
              this.$refs['editForm'].validate(valid => {
                if (valid) {
                  // 添加流程
                  this.$http
                    .raw('api/insertFlow', params)
                    .then(res => {
                      let { code } = res;
                      // 判断Code状态
                      if (code === 0) {
                        this.$message({
                          message: '添加成功！',
                          type: 'success'
                        });
                        // 初始化弹窗表单数据
                        this.$refs['editForm'].resetFields();
                        this.goBack();
                      }
                    })
                    .catch(err => {
                      if (err === undefined) {
                        this.$message({
                          message: '服务器响应异常！',
                          type: 'error'
                        });
                        return false;
                      }
                    });
                }
              });
            }
          }
        }).catch(err => {
          if (err === undefined) {
            this.$message({
              message: '服务器响应异常！',
              type: 'error'
            });
            return false;
          }
        });
      });
    },

    // 修改流程
    onEdit () {
      // 防止重复提交
      this.isSubmit = true;
      setTimeout(() => {
        this.isSubmit = false;
      }, 1000);
      this.$nextTick(() => {
        // 收集请求数据
        let params = {
          id: this.editForm.id,
          compId: this.editForm.compId,
          // 流程表
          flowId: this.editForm.flowId,
          flowName: this.editForm.flowName,
          flowType: this.editForm.flowType,
          formId: this.editForm.formId,
          note: this.editForm.note,
          flowJson: '',
          // 流程节点表
          flowNode: [],
          // 流程线条表
          flowLine: []
        };

        let flows = this.$refs.flowChart.propsAPI.save();

        params.flowJson = JSON.stringify(flows);

        if (flows.nodes !== undefined) {
          flows.nodes.map(item => {
            params.flowNode.push({
              // 节点ID
              id: item.id,
              // 节点名称
              name: item.label,
              // 节点类型
              type: item.type,
              // 节点处理人
              users: item.users
            });
          });
        }
        if (flows.edges !== undefined) {
          flows.edges.map(ind => {
            params.flowLine.push({
              // 线条ID
              id: ind.id,
              // 线条名称
              name: ind.label,
              // 上一步节点
              source: ind.source,
              // 下一步节点
              target: ind.target
            });
          });
        }
        // 判断是否通过验证规则验证
        this.$refs['editForm'].validate(valid => {
          if (valid) {
            // 添加流程
            this.$http
              .raw('api/updateFlow', params)
              .then(res => {
                let { code } = res;
                // 判断Code状态
                if (code === 0) {
                  this.$message({
                    message: '修改成功！',
                    type: 'success'
                  });
                  // 初始化弹窗表单数据
                  this.$refs['editForm'].resetFields();
                  this.goBack();
                }
              })
              .catch(err => {
                if (err === undefined) {
                  this.$message({
                    message: '服务器响应异常！',
                    type: 'error'
                  });
                  return false;
                }
              });
          }
        });
      });
    },

    // 返回
    goBack () {
      this.$router.push({ path: '/home/processModel' });
    }
  },

  data () {
    return {

      compList: [],
      formList: [],

      isSubmit: false,
      isEdit: false,

      editForm: {
        compId: '',
        flowId: '',
        // 流程表
        flowName: '',
        flowType: '',
        formId: '',
        note: '',
        flowJson: '',
        // 流程节点表
        flowNode: {},
        // 流程线条表
        flowLine: {}
      },

      editFormRules: {
        compId: [{
          required: true, message: '请选择公司名称', trigger: 'change'
        }],
        flowId: [
          { required: true, message: '请输入流程编号', trigger: 'blur' }
        ],
        flowName: [
          { required: true, message: '请输入流程名称', trigger: 'blur' }
        ],
        flowType: [
          { required: true, message: '请选择流程类型', trigger: 'change' }
        ],
        formId: [
          { required: true, message: '请选择关联表单', trigger: 'change' }
        ]
      },

      modalVisible: false,
      nodeData: {},
      flowChartData: data,
      customEdgeConfig: {
        getActivedStyle (item) {
          return {
            lineWidth: 3
          };
        },
        getSelectedStyle (item) {
          return {
            lineWidth: 3
          };
        }
      }
    };
  },
  components: {
    VGEditor,
    Flow,
    FlowToolbar,
    FlowItemPanel,
    FlowDetailPanel,
    EditorMinimap,
    FlowContextMenu,
    RegisterEdge,
    NodeData
  },
  created () {
    // 获取所有公司数据
    this.getCompList();

    // 获取所有表单数据
    this.getFormList();

    // 判断是否修改
    this.getDatas();
  }
};
</script>

<style lang='scss' scoped>
@import './index.scss';
</style>
